package com.neu.util;

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


@Component
public class EmailUtil {
    @Autowired
    private JavaMailSender sender = null;

    public void sendEmail(String to,String subject,String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(((JavaMailSenderImpl)sender).getUsername());//获取xml内的发送源邮箱
        mailMessage.setTo(to);//发送给谁
        mailMessage.setSubject(subject);//标题
        mailMessage.setText(content);//内容
        sender.send(mailMessage);//发送
        System.out.println("发送成功");
    }

    public void sendFileEmail(String to,String subject,String html,File[] files) {
        try {
            MimeMessage mi = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mi,true,"utf-8");
            helper.setFrom(((JavaMailSenderImpl)sender).getUsername());//获取xml内的发送源邮箱
            helper.setTo(to);//发送给谁
            helper.setSubject(subject);//标题
            helper.setText(html,true);//内容
            for(File f : files) {
                helper.addAttachment(f.getName(), f);
            }
            sender.send(mi);//发送
            System.out.println("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}

